/*
 *  BaiDuSdkUtils.java
 *  business
 *
 *  Created by SunDing on 2016/11/3.
 *
 *  Copyright (c) 2016年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.utils;

import android.app.Activity;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.yidiandao.business.R;
import com.yidiandao.business.constant.Preferences;
import com.yidiandao.business.data.event.RefreshDataEvent;
import com.yidiandao.business.data.model.AddressModel;
import com.yidiandao.business.data.model.IAddressModel;
import com.yidiandao.business.data.model.IUserModel;
import com.yidiandao.business.data.model.UserModel;
import com.yidiandao.business.ui.widget.dialog.BusinessDialog;
import com.yidiandao.business.ui.widget.dialog.LoadingDialog;
import com.yidiandao.business.ui.widget.view.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * 百度定位 位置切换
 */
public class BaiDuSdkHelper {

    private LocationClient mLocationClient;

    private LocationListener myListener = new LocationListener();

    private Activity mActivity;

    private String mTag;

    private IUserModel mUserModel;

    private LoadingDialog mLoadingDialog;
    /**
     * 已开通服务的城市
     */
    private List<String> mCitys = new ArrayList<>();
    /**
     * 当前定位的城市
     */
    private String mCurrentCity = "";

    private TextView mLocationTextView;

    /**
     * 是否正在定位中
     */
    private boolean isLoading;

    public BaiDuSdkHelper(Activity activity) {
        mActivity = activity;
    }

    public void getAddress(String tag) {
        init();
        mTag = tag;
        mUserModel = new UserModel();
        start();
    }

    private void init() {
        initConfig();
        initDialog();
    }

    private void initDialog() {
        mLoadingDialog = new LoadingDialog(mActivity);
        mLoadingDialog.setCanceledOnTouchOutside(false);
    }

    public void initConfig() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(
                LocationClientOption.LocationMode.Hight_Accuracy); //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll"); //可选，默认gcj02，设置返回的定位结果坐标系
        int span = 1000;
        option.setScanSpan(span); //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true); //可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true); //可选，默认false,设置是否使用gps
        option.setLocationNotify(true); //可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(
                true); //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation
        // .getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true); //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(
                false); //可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
        option.SetIgnoreCacheException(false); //可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false); //可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        option.setTimeOut(5000);

        //声明LocationClient类
        mLocationClient = new LocationClient(UIUtils.getContext());

        mLocationClient.setLocOption(option); //设置参数
    }

    public void start() {
        if (mLocationClient != null && !mLocationClient.isStarted()) {
            mLocationClient.registerLocationListener(myListener); //注册监听函数
            mLocationClient.start();
            isLoading = true;
        }
    }

    /**
     * 设置已开通服务的城市 和要显示定位信息的view
     */
    public void setCanUseCitys(List<String> citys, TextView locationTextView) {
        mLocationTextView = locationTextView;
        mCitys.clear();
        mCitys.addAll(citys);
    }

    /**
     * 获取当前定位的城市
     */
    public String getCurrentCity() {
        return mCurrentCity;
    }

    /**
     * 设置当前定位城市
     */
    private void setTextLoaction(String city) {
        mCurrentCity = city;
        if (TextUtils.isEmpty(city)) {
            mLocationTextView.setText(UIUtils.getString(R.string.location_error));
        } else {
            mLocationTextView.setText(city);
        }
    }

    /**
     * @return 是否正在定位中
     */
    public boolean getIsLoading() {
        return isLoading;
    }

    /**
     * 弹出提示
     *
     * @param city      当前定位城市
     * @param select    选择的城市
     * @param tagLayout 管理tag的layout
     */
    public void alertDialog(final String city, final String select, final TagFlowLayout tagLayout) {
        if (city.equals(select)) {
            getHost(mTag, select);
        } else {
            new BusinessDialog.Builder(mActivity)
                    .setTitle(
                            TextUtils.isEmpty(city)
                                    ? UIUtils.getString(R.string.location_change_error, select)
                                    : UIUtils.getString(R.string.location_change, city, select))
                    .setPositiveButton(
                            R.string.confirm,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    RealmUtils.clearBrowsingHistory(mActivity);
                                    mUserModel.clearUserInfo(false);
                                    getHost(mTag, select);
                                }
                            })
                    .setNegativeButton(
                            R.string.cancel,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    tagLayout.clearAllSelected();
                                }
                            })
                    .create()
                    .show();
        }
    }

    public void getHost(String tag, final String city) {
        showDialog();
        final AddressModel model = new AddressModel();
        model.getAddressChangeHost(tag, city, new IAddressModel.OnAccessNetListener<String>() {
            @Override
            public void onSuccess(String host) {
                dismissDialog();
                PreferenceUtils.setString(UIUtils.getContext(), Preferences.CITY, city, true);
                PreferenceUtils.setString(UIUtils.getContext(), Preferences.HOST, host, true);
                EventBus.getDefault().post(new RefreshDataEvent());
            }

            @Override
            public void onFailed() {
                UIUtils.showToast(UIUtils.getString(R.string.dialog_tip12));
                dismissDialog();
                if (null == mUserModel) {
                    mUserModel = new UserModel();
                }
                mUserModel.clearUserInfo(false);
            }
        });
    }

    public void closeLocation() {
        if (mLocationClient != null && mLocationClient.isStarted()) {
            mLocationClient.stop();
            mLocationClient.unRegisterLocationListener(myListener);
        }
    }

    public void showDialog() {
        if (null != mLoadingDialog && !mLoadingDialog.isShowing()) {
            mLoadingDialog.show();
        }
    }

    public void dismissDialog() {
        if (null != mLoadingDialog && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    /**
     * 监听函数
     */
    public class LocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            isLoading = false;
            mLocationClient.stop();
            mLocationClient.unRegisterLocationListener(myListener);
            String city = "";
            if (!(null == location || TextUtils.isEmpty(location.getLocationDescribe()))) {
                city = location.getCity();
            }
            /* 与上次定位不一样
             * 1.定位失败 为空
             *     1)上次定位在深圳
             *     2)不在
             * 2.定位成功 不为空
             *    1） 在服务区 深圳  东莞
             *    2） 不在
             *       1))上次定位在深圳  只提示
             *       2))不在  提示切换
             * */
            //去掉 最后一个市
            if (city.indexOf("市") == city.length() - 1) {
                city = city.replace("市", "");
            }
            setTextLoaction(city);
            /*  if (!city.equals(PreferenceUtils.getString(UIUtils.getContext(), Preferences
            .CITY, UIUtils.getString(R.string.address_shenzhen), true))) {
                //定位失败 为空
                if (TextUtils.isEmpty(city)) {
                    //且上次定位不在深圳
                    if (!UIUtils.getString(R.string.address_shenzhen).equals(PreferenceUtils
                    .getString(UIUtils.getContext(), Preferences.CITY, UIUtils.getString(R.string
                    .address_shenzhen), true))) {
                        city = UIUtils.getString(R.string.address_shenzhen);//定位失败 默认深圳
                        message = UIUtils.getString(R.string.dialog_tip9);
                        alertDialog(city, message);
                    }
                } else {
                    //定位成功   在服务区 深圳  东莞
                    if (city.equals(UIUtils.getString(R.string.address_shenzhen)) || city.equals
                    (UIUtils.getString(R.string.address_dongguan))) {
                        message = UIUtils.getString(R.string.dialog_tip8, city);

                    } else {
                        //不在服务区
                        if (UIUtils.getString(R.string.address_shenzhen).equals(PreferenceUtils
                        .getString(UIUtils.getContext(), Preferences.CITY, UIUtils.getString(R
                        .string.address_shenzhen), true))) {
                            //若是上次定位在深圳
                            city = "";
                            message = UIUtils.getString(R.string.dialog_tip13);
                        } else {
                            city = UIUtils.getString(R.string.address_shenzhen);//提示切换深圳
                            message = UIUtils.getString(R.string.dialog_tip10);
                        }
                    }
                    alertDialog(city, message);
                }
            }*/
        }
    }
}
